package com.easychat;

import com.easychat.websocket.netty.NettyWebSocketStarter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component("initRun")
//@Slf4j
public class InitRun implements ApplicationRunner {

    @Resource
    private DataSource dataSource;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private NettyWebSocketStarter nettyWebSocketStarter;

    /**
     * 实现ApplicationRunner接口，重写run方法，在程序启动完成后执行
     * 检测mysql和redis连接情况
     * 创建新线程，启动netty服务器
     * @param args
     */
    @Override
    public void run(ApplicationArguments args){
        try {
            dataSource.getConnection();
            redisTemplate.opsForValue().set("city", "潜江");
            new Thread(nettyWebSocketStarter).start();//另外起一个线程执行，否则netty启动后会阻塞在这里
            //log.info("服务启动成功，可以开始开发了");
        } catch (SQLException e) {
            //log.error("数据库连接失败，请检查数据库配置");
        } catch (RedisConnectionFailureException e) {
            //log.error("redis连接失败，请检查redis配置");
        } catch (Exception e) {
            //log.error("发生未知错误");
        }
    }
}
